<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="户号" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入户号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="户名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="表号" prop="meterNo">
        <el-input v-model="queryParams.meterNo" placeholder="请输入表号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="通知单日期" prop="adviceDate">
        <el-date-picker clearable
          v-model="queryParams.adviceDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择通知单日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['revenue:bill:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['revenue:bill:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['revenue:bill:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['revenue:bill:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="billList" @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
<!--       <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="户号" align="center" prop="userId" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="户名" align="center" prop="userName" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="表号" align="center" prop="meterNo"/>
      <el-table-column label="用水地址" align="center" prop="address" />
      <el-table-column label="上次抄码" align="center" prop="meterReadLast" />
      <el-table-column label="本次抄码" align="center" prop="meterReadNow" />
      <el-table-column label="本次水量(m³)" align="center" prop="usageAmount" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="水费金额(元)" align="center" prop="totalAmount" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="通知单日期" align="center" prop="adviceDate" width="180" sortable="custom"
                       :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.adviceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-printer" @click="handlePrint(scope.row)"
            v-hasPermi="['revenue:bill:edit']">打印</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['revenue:bill:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['revenue:bill:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改水费账单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="户号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入户号" />
        </el-form-item>
        <el-form-item label="户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入户名" />
        </el-form-item>
        <el-form-item label="表号" prop="meterNo">
          <el-input v-model="form.meterNo" placeholder="请输入表号" />
        </el-form-item>
        <el-form-item label="用水地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入用水地址" />
        </el-form-item>
        <el-form-item label="上次抄码" prop="meterReadLast">
          <el-input v-model="form.meterReadLast" placeholder="请输入上次抄码" />
        </el-form-item>
        <el-form-item label="本次抄码" prop="meterReadNow">
          <el-input v-model="form.meterReadNow" placeholder="请输入本次抄码" />
        </el-form-item>
        <el-form-item label="本次水量(m³)" prop="usageAmount">
          <el-input v-model="form.usageAmount" placeholder="请输入本次水量(m³)" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="水费金额(元)" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入水费金额(元)" />
        </el-form-item>
        <el-form-item label="通知单日期" prop="adviceDate">
          <el-date-picker clearable v-model="form.adviceDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择通知单日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listBill, getBill, delBill, addBill, updateBill } from "@/api/revenue/bill";

  export default {
    name: "Bill",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 默认排序
        defaultSort: { prop: 'adviceDate', order: 'descending' },
        // 总条数
        total: 0,
        // 水费账单表格数据
        billList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userId: null,
          userName: null,
          meterNo: null,
          adviceDate: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          userId: [
            { required: true, message: "户号不能为空", trigger: "blur" }
          ],
          usageAmount: [
            { required: true, message: "本次水量(m³)不能为空", trigger: "blur" }
          ],
          unitPrice: [
            { required: true, message: "单价不能为空", trigger: "blur" }
          ],
          totalAmount: [
            { required: true, message: "水费金额(元)不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询水费账单列表 */
      getList() {
        this.loading = true;
        listBill(this.queryParams).then(response => {
          this.billList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          billNumber: null,
          userId: null,
          userName: null,
          address: null,
          meterReadLast: null,
          meterReadNow: null,
          usageAmount: null,
          unitPrice: null,
          totalAmount: null,
          adviceDate: null,
          remark: null,
          meterNo: null,
          billingDate: null,
          month: null,
          billingCycleStart: null,
          billingCycleEnd: null,
          amountDue: null,
          paidAmount: null,
          billStatus: null,
          dueDate: null,
          paymentDate: null,
          createTime: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加水费账单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getBill(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改水费账单";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateBill(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBill(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除水费账单编号为"' + ids + '"的数据项？').then(function () {
          return delBill(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('revenue/bill/export', {
          ...this.queryParams
        }, `bill_${new Date().getTime()}.xlsx`)
      },
      //打印
      handlePrint(row) {
        this.reset();
        const id = row.id || this.ids;
        getBill(id).then(response => {
          const billData = response.data;

          // 创建打印内容
          const printContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>水费通知单打印</title>
                <meta charset="utf-8">
                <style>
                    body {
                        font-family: "Microsoft YaHei", sans-serif;
                        margin: 0;
                        padding: 20px;
                        color: #000;
                    }
                    .print-container {
                        width: 800px;
                        margin: 0 auto;
                        padding: 30px;
                        background: white;
                        position: relative;
                    }
                    .company-name {
                        text-align: center;
                        font-size: 24px;
                        font-weight: bold;
                        margin-bottom: 10px;
                    }
                    .date-container {
                        text-align: right;
                        margin: 0 50px 30px 0;
                        font-size: 16px;
                    }
                    .stamp {
                        position: absolute;
                        right: 100px;
                        top: 80px;
                        color: #f56c6c;
                        font-size: 14px;
                        opacity: 0.8;
                    }
                    .bill-table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 25px;
                        border: 1px solid #000;
                    }
                    .bill-table td {
                        border: 1px solid #000;
                        padding: 12px 15px;
                        font-size: 14px;
                        height: 40px;
                    }
                    .bill-table .label {
                        background-color: #f5f5f5;
                        font-weight: bold;
                        width: 120px;
                        text-align: center;
                    }
                    .payment-info {
                        padding: 15px;
                        background-color: #f9f9f9;
                        margin-bottom: 20px;
                        font-size: 14px;
                        line-height: 1.6;
                    }
                    .payment-info .important {
                        color: #f00;
                        font-weight: bold;
                        margin-bottom: 10px;
                    }
                    .bank-info {
                        margin-top: 15px;
                    }
                    @media print {
                        body {
                            padding: 0;
                        }
                    }
                </style>
            </head>
            <body>
                <div class="print-container">
                    <div class="company-name">郑州航空港区泓港水资源开发有限公司水费通知单</div>
                    <div class="date-container">${this.parseTime(billData.adviceDate, '{y}年{m}月{d}日')}</div>

                    <table class="bill-table">
                     <tr>
                            <td class="label">户号</td>
                            <td>${billData.userId || ''}</td>
                            <td class="label">户名</td>
                            <td>${billData.userName || ''}</td>
                            <td class="label">备注</td>
                        </tr>
                        <tr>
                            <td class="label">用水地址</td>
                            <td colspan="3">${billData.address || ''}</td>
                        </tr>
                        <tr>
                            <td class="label">上次抄码</td>
                            <td>${billData.meterReadLast || 0}</td>
                            <td class="label">本次抄码</td>
                            <td>${billData.meterReadNow || 0}</td>
                        </tr>
                        <tr>
                            <td class="label">本次水量(m³)</td>
                            <td>${billData.usageAmount || 0}</td>
                            <td class="label">单价(元)</td>
                            <td>${billData.unitPrice || 0}</td>
                        </tr>
                        <tr>
                            <td class="label">水费金额(元)</td>
                            <td colspan="3">${billData.totalAmount || 0}</td>
                        </tr>
                    </table>

                    <div class="payment-info">
                        <div class="important">请贵单位于${this.getDueDate(billData.adviceDate)}前完成水费缴纳，逾期不交，按供水条例规定，将收取每日0.1%的违约金。</div>
                        <div>联系电话: 13903819996</div>

                        <div class="bank-info">
                            <div>一、银行缴费</div>
                            <div>公司名称: 郑州航空港区泓港水资源开发有限公司</div>
                            <div>开户行: 中国银行股份有限公司郑州航空港分行营业部</div>
                            <div>银行账号: 261193711227</div>
                        </div>

                        <div>二、公司现场缴费地址: 郑州市航空港洵美路16号7号楼4层402号。</div>
                    </div>
                </div>
            </body>
            </html>
        `;

          // 创建打印窗口
          const printWindow = window.open('', '_blank', 'width=900,height=700');
          printWindow.document.write(printContent);
          printWindow.document.close();

          // 等待内容加载完成后打印
          printWindow.onload = function () {
            printWindow.print();
            // 打印后可以选择关闭窗口
            printWindow.close();
          };
        }).catch(error => {
          console.error('获取账单数据失败:', error);
          this.$message.error('获取账单数据失败，请重试');
        });
      },

      // 辅助方法：计算缴费截止日期（通知单日期+5天）
      getDueDate(adviceDate) {
        if (!adviceDate) return '指定日期';

        const date = new Date(adviceDate);
        date.setDate(date.getDate() + 5);

        return this.parseTime(date, '{y}年{m}月{d}日');
      },

      // 时间格式化方法
      parseTime(time, format) {
        if (!time) return '';

        const date = new Date(time);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');

        return format.replace('{y}', year)
          .replace('{m}', month)
          .replace('{d}', day);
      }
    }
  };
</script>
